<?php

/**
 * 角色权限
 * 
 * @author jinyue.wang
 * @version 1.0
 * @date 2013-12-12
 */
class DefaultController extends FController {

    public function accessRules() {
        $config = array(
            'index' => 1
        );
        return ZRole::auth("role", $config);
    }

    public function __common() {
        parent::init();
        if (empty($this->cLoginUser)) {
            $this->redirect($this->createUrl('/site/login'));
        }

        $this->commonScript();
        Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/module_Sip.css');
    }

    /**
     * 角色列表显示
     * 
     * @version 1.0
     * @author jinyue.wang
     * @date 2013-12-12
     */
    public function actionIndex() {

        $this->__common();

        $s = array();
        
        $s['role_name'] = $this->request->getParam('role_name');
        $s['role_code'] = $this->request->getParam('role_code');

        $s = Func::dis_input($s);
        $s = Func::fAddslashes($s);
        $where = ' WHERE 1=1 ';
        $where .= (Func::dis_search($s['role_name']))  ? 'AND "role_name" LIKE \'%'.$s['role_name'].'%\'': '';
        $where .= (Func::dis_search($s['role_code'])) ?'AND "role_code" LIKE \'%'.$s['role_code'].'%\'': '';
        
        //$order = ' ORDER BY "listorder" ASC ';
        $order = ' ORDER BY "role_code" ';
        
        $sqlSelect = 'SELECT "role_id","role_name","role_code","disabled","description" FROM "{{role}}" ';
        $sqlCount = 'SELECT COUNT(*) FROM "{{role}}"';
        
        $sqlSelect .= $where.$order;
        $sqlCount .= $where.$order;
        
        $data = ZCommon::getDaoPageList($sqlSelect, $sqlCount, 8);
        $this->title = '角色信息维护';
        $pageUrl = Yii::app()->request->getUrl();
        $pageUrl = $this->createUrl("/role/default/index", $s);

        $this->render('index', array(
            'data' => isset($data['listDatas']) ? $data['listDatas'] : '',
            'pages' => isset($data['pages']) ? $data['pages'] : '',
            'pageUrl' => $pageUrl,
            'search' => $s
        ));
    }

    /**
     * 功能需求列表
     * 
     * @version 1.0
     * @author jinyue.wang
     * @date 2013-12-12
     */
    public function actionMenu() {

        $this->__common();

        $priv_data = '';
        $where = ' WHERE 1=1 ';

        $tree = new Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        $zEdu = new ZEdu();
        $menuArray = $zEdu->_getMenuData($where);

        if (!empty($menuArray)) {
            foreach ($menuArray as $mKey => $mVal) {
                $menuArray[$mKey]['is_show'] = "";
                $menuArray[$mKey]['is_show'] = "<a href='javascript:;' onclick='edit(" . $mVal['id'] . "," . $mVal['parentid'] . ")' title='编辑'><img src='/themes/default/images/Sipei/edit.png' class='pr15' /></a>";
                if ($mVal['disabled'] != null) {
                    $menuArray[$mKey]['is_show'] .= "<a href='javascript:;' onclick='del(" . $mVal['id'] . "," . $mVal['parentid'] . ")' title='删除'><img src='/themes/default/images/Sipei/delate.png'/></a>";
                }
                /*$menuArray[$mKey]['is_show'] = "<a href='javascript:;' onclick='edit(" . $mVal['id'] . "," . $mVal['parentid'] . ")' title='编辑'><img src='/themes/default/images/Sipei/edit.png' class='pr15' /></a>
                        <a href='javascript:;' onclick='del(" . $mVal['id'] . "," . $mVal['parentid'] . ")' title='删除'><img src='/themes/default/images/Sipei/delate.png'/></a>";*/
            }
        }
        //需要增加内容
        $str = "<tr>
                    <td align='left' class='m_hr_b pl20'>\$ename</td>
                    <td align='left' class='m_hr_b pl5'>\$spacer\$cname</td>
                    <td align='left' class='m_hr_b'>\$m/\$c/\$a</td>
                    <td align='center' class='m_hr_b height20 pt5 pb5'>\$comment</td>
                    <td align='center' class='m_hr_b'>
                        <!--<a href='javascript:;' onclick='add(\$id,\$parentid)' title='添加子菜单'><img src='/themes/default/images/Sipei/plus.png' class='pr15' /></a>
                        <a href='javascript:;' onclick='edit(\$id,\$parentid)' title='编辑'><img src='/themes/default/images/Sipei/edit.png' class='pr15' /></a>
                        <a href='javascript:;' onclick='del(\$id,\$parentid)' title='删除'><img src='/themes/default/images/Sipei/delate.png'/></a>-->
                        \$is_show
                    </td>
                </tr>";

        $tree->init($menuArray);
        $categorys = $tree->get_tree(0, $str);

        $this->title = "功能菜单维护";
        $this->render('menu', array(
            'categorys' => $categorys
        ));
    }

    /**
     * 编辑功能
     * 
     * @version 1.0
     * @author jinyue.wang
     * @date 2013-12-13
     */
    public function actionUpdate() {

        $this->layout = "//layouts/main_window";
        $mid = $this->request->getParam('mid');
        $parent_id = $this->request->getParam('pid');

        $zEdu = new ZEdu();
        if (isset($_POST) && !empty($_POST)) {

            $data = ZTask::dis_input($_POST);
            if ($_POST['mid'] == $data['parentid']) {
                $data['parentid'] = 0;
            }

            $status = $zEdu->_updRoleMenu($_POST['mid'], $data);
            if($status){
             	 $this->frameAjaxMessage('menu');
             	 exit;
            }else{
            	 $this->frameAjaxMessage(null,'更新失败');
            	 exit;
            }
           
            exit;
        }

        $tree = new Tree();
        $tree->icon = array('&nbsp;│ ', '&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;';

        $model_menu = array();
        $where = " WHERE 1=1 ";
        $menuArray = $zEdu->_getMenuData($where);
        if (!empty($menuArray)) {
            foreach ($menuArray as $key => $value) {
                $select = '';
                if ($value['id'] == $parent_id) {
                    $select = "selected";
                }

                if ($value['id'] == $mid) {
                    if ($parent_id == 0) {
                        $select = "selected";
                    }
                    $model_menu = $value;
                }

                $menuArray[$key]['select'] = $select;
            }
        }

        //需要增加内容
        $str = "<option value='\$id' \$select>\$spacer\$cname</option>";
        $tree->init($menuArray);
        $option = $tree->get_tree(0, $str);

        $this->render('update', array(
            'option' => $option,
            'model_menu' => $model_menu,
            'mid' => $mid
        ));
    }

    /**
     * 功能添加
     * 
     * @version 1.0
     * @author jinyue.wang
     * @date 2013-12-14
     */
    public function actionAdd() {

        // $this->__common();
        $this->layout = "//layouts/main_window";

        $tree = new Tree();
        $tree->icon = array('&nbsp;│ ', '&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;';

        $mid = $this->request->getParam('mid');

        $model_menu = array();

        $zEdu = new ZEdu();
        if (isset($_POST) && !empty($_POST)) {
            $data = ZTask::dis_input($_POST);
            $status = $zEdu->_updRoleMenu(0, $data);
			
            if($status){
                $this->frameAjaxMessage('/role/default/menu');
                exit;
            }else{
                $this->frameAjaxMessage(null,'添加失败');
            }
            exit;
        }

        $where = ' WHERE "display" = 1 ';
        $menuArray = $zEdu->_getMenuData($where);
        if (!empty($menuArray)) {
            foreach ($menuArray as $key => $value) {

                $select = '';
                if ($mid == $value['id']) {
                    $select = "selected";
                }
                $menuArray[$key]['select'] = $select;
            }
        }

        //需要增加内容
        $str = "<option value='\$id' \$select>\$spacer\$cname</option>";

        $tree->init($menuArray);
        $option = $tree->get_tree(0, $str);

        $this->render('add', array(
            'option' => $option,
            'mid' => $mid
        ));
    }

    /**
     * 用户信息维护页面
     * 
     * @version 1.0
     * @date 2013-12-13
     * @author jinyue.wang
     */
    public function actionRole_user() {

        $this->__common();

        $s = array();
        

        $s['role'] = $this->request->getQuery('role', '');
        $s['username'] = $this->request->getQuery('username', '');
        $s['subject'] = $this->request->getQuery('subject', '');
        $s['school'] = $this->request->getQuery('school', '');
        $s['status'] = $this->request->getQuery('status', '');
        $s['comment'] = $this->request->getQuery('comment', '');

        $s = Func::dis_input($s);
        $s = Func::fAddslashes($s);
	
        $where = ' WHERE 1=1 ';
        $where .= $s['role'] ? ' AND A."role_id"=\''. $s["role"].'\'' : '';
        $where .= $s['subject'] ? ' AND B."subject_id" = \''.$s["subject"].'\'' : '';
        $where .= $s['school'] ? ' AND B."school_id" = \''.$s['school'].'\'': '';
        $where .= $s['status'] ? ' AND A."status" = 1 ' : "";
        $where .= (Func::check_search($s['username'])) ? ' AND A."username" LIKE \'%'.$s['username'].'%\'' : "";
        $where .= (Func::check_search($s['comment'])) ? ' AND A."comment" LIKE \'%'.$s['comment'].'%\'' : "";
        $order = ' ORDER BY A."username"';

        $sqlSelect = 'SELECT A."id",A."username",A."role_id",A."lastlogin_ip",A."lastlogin_time",A."email",A."realname",A."status",A."comment",B."school_id",B."subject_id" FROM "{{user}}" A LEFT JOIN "{{user_school}}" B ';
        $sqlSelect .= ' ON A."id" = B."user_id" ';
        $sqlCount = 'SELECT count(*) FROM "{{user}}" A LEFT JOIN "{{user_school}}" B ';
        $sqlCount .= ' ON A."id" = B."user_id" ';

        $sqlSelect .= $where . $order;
        $sqlCount .= $where . $order;
        $zUser = new ZUser();
        $school_object = $zUser->_getSchoolObject();

        $zEdu = new ZEdu();
        $subject_object = $zEdu->_getSubjectObject();

        $data = ZCommon::getDaoPageList($sqlSelect, $sqlCount, 8);
        if(isset($data['listDatas']) && !empty($data['listDatas'])){

            foreach ($data['listDatas'] as $key => $value) {              
                //得到学校信息
                $data['listDatas'][$key]['school_name'] = '';
                $data['listDatas'][$key]['subject_name'] = '';
                $school = array();
                if (!empty($value['school_id'])) {
                    $school = explode(',', $value['school_id']);
                    $sum = count($school);
                    foreach ($school as $k => $one) {
                        if (isset($school_object[$one])) {
                            $data['listDatas'][$key]['school_name'] .= $school_object[$one]['school_name'];
                            if ($sum != $k + 1) {
                                $data['listDatas'][$key]['school_name'] .=",";
                            }
                        }
                    }
                }  else {
                    $data['listDatas'][$key]['school_name'] ="";
                }
                if (!empty($value['subject_id'])) {
                    $subject = explode(',', $value['subject_id']);
                    $subsum = count($subject);
                    //得到科目信息
                    foreach ($subject as $ke => $one) {
                        if (isset($subject_object[$one])) {
                            $data['listDatas'][$key]['subject_name'] .= $subject_object[$one]['subject_name'];
                            if ($subsum != $ke + 1) {
                                $data['listDatas'][$key]['subject_name'] .=",";
                            }
                        }
                    }
                }  else {
                  $data['listDatas'][$key]['subject_name'] =" ";   
                }
            }
        }
        $roleObject = $zEdu->_getRoleObject();
        
        $loginUser = $this->cLoginUser;
        $user_id = $role_id = 0;
        if(!empty($loginUser)){
            $user_id = $loginUser['cuser']['id'];
            $role_id = $loginUser['cuser']['role_id'];
        }
        
        $this->title = '用户信息维护';
        $pageUrl = Yii::app()->request->getUrl();
        $pageUrl = $this->createUrl("/role/default/role_user", $s);
        $this->render('role_user', array(
            'data'              => isset($data['listDatas']) ? $data['listDatas'] : '',
            'pages'             => isset($data['pages']) ? $data['pages'] : '',
            'roleObject'        => $roleObject,
            'school_object'     => $school_object,
            'subject_object'    => $subject_object,
            'pageUrl'           => $pageUrl,
            'user_id'           => $user_id,
            'role_id'           => $role_id,
            's'                 => $s
        ));
    }

    /**
     * 用户角色功能
     * 
     * @author jinyue.wang
     * @version 1.0
     * @date 2013-12-15
     */
    public function actionUpd_priv() {

        //$this->__common();
        $this->layout = "//layouts/main_window";

        $zEdu = new ZEdu();
        $rid = $this->request->getParam('rid');

        if (isset($_POST['submit']) && !empty($_POST)) {
            $_POST['role_code'] = strtolower($_POST['role_code']);
            $model = Role::model()->find(' "role_code" = \'' . $_POST['role_code'] . '\' AND "role_id" !=' . $_POST["role_id"]);
            if (!empty($model)) {
                $this->frameAjaxMessage(null, '角色代码已被占用!');
                exit;
            }

            $status = $zEdu->_updUserRoe($_POST['role_id'], $_POST);

            $this->frameAjaxMessage('/role/default/index');exit;
        }

        $tree = new Tree();
        $tree->icon = array('&nbsp;│ ', '&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;';

        //需要增加内容  
        $roleObject = $zEdu->_getRoleArray($rid);

        //得到用户权限
        $rolePrive = $zEdu->_getRolePrive($rid);
        
        $where = 'WHERE "display" = 1 ';
        $menuArray  = $zEdu->_getMenuData($where);

        if(!empty($menuArray)){
            foreach($menuArray as $key => $value){
                $check = '';
                if(in_array($value['id'], $rolePrive)): $check = 'checked'; endif;
                
                $menuArray[$key]['cbox'] = " <input type='checkbox' class='parent_".$value['parentid']."' name='menu_id[]' ".$check." value='".$value['id']."'>";
                
                $menuArray[$key]['ckey'] = '';
                if($value['parentid'] ==0){
                    $menuArray[$key]['ckey'] = "<a class='cursor click_on'><img src='".THEME_IMAGES_URL."/Sipei/uAdd.png'></a>";
                }
            }
        }
        
        $str = "<ul class='treeBox'>
                    <li>\$spacer\$ckey\$cname\$cbox</li>
                </ul>";
        
        $tree->init($menuArray);
        $list = $tree->get_tree(0, $str);
        
        $this->render('role_priv',array(
            'list'          => $list,
            'rid'           => $rid,
            'roleObject'    => $roleObject
        ));
    }
    
    /**
     * 添加角色 
     * 
     * @author jinyue.wang
     * @version 1.0
     * @date 2013-12-16
     */
    public function actionAdd_role() {

        $this->layout = "//layouts/main_window";

        if (isset($_POST['submit']) && !empty($_POST)) {

            $sta = 0;

            if (!empty($_POST['check'])) {
                $sta = 1;
            }
            $_POST['role_code'] = strtolower($_POST['role_code']);
            $model = Role::model()->find(' "role_code" = \'' . $_POST['role_code'] . '\'');
            if (!empty($model)) {
                $this->frameAjaxMessage(null, '角色代码已被占用!');
                exit;
            }

            $sql = 'INSERT INTO "{{role}}"("role_name","role_code","description","disabled") VALUES (:role_name,:role_code,:content,:sta)';
            $result = Yii::app()->db->createCommand($sql);
            $result->bindParam(':role_name', $_POST['role_name'], PDO::PARAM_STR);
            $result->bindParam(':role_code', $_POST['role_code'], PDO::PARAM_STR);
            $result->bindParam(':content', $_POST['content'], PDO::PARAM_STR);
            $result->bindParam(':sta', $sta, PDO::PARAM_STR);

            $status = $result->execute();

            //$this->redirect($this->createUrl('/role/default/index'));
            $this->frameAjaxMessage(null, null,true);
            exit;
        }

        $this->render('add_role', array());
    }
    
    /**
     * 删除角色
     * 
     * @return boolean
     * 
     * @author jinyue.wang
     * @version 1.0
     * @date 2013-12-29
     */
    public function actionDelete(){
        
        $this->__common();
        
        $status = 0;
        
        $id = $this->request->getParam('id');
        if ($id > 0) {

            $model = User::model()->find(' "role_id" = ' . $id);
            if (!empty($model)) {
                echo 2;
                exit;
            }

            $sql = 'DELETE FROM "{{role}}" WHERE "role_id" = :role_id ';
            $result = Yii::app()->db->createCommand($sql);
            $result->bindParam(':role_id',$id,PDO::PARAM_STR);
            
            $status = $result->execute();
            
        }
        echo $status;
    }
    
    /**
     * 删除菜单
     * 
     * @author jinyue.wang
     * @date 2013-12-18
     * @version 1.0
     */
    public function actionDel_menu(){
        
        $mid = $this->request->getParam('mid');

        if($mid>0){
            
            $sql = 'DELETE FROM "{{menu}}" WHERE "id" = :id ';
            $result = Yii::app()->db->createCommand($sql);
            $result->bindParam(':id',$mid,PDO::PARAM_STR);
            
            $status = $result->execute();
            if($status){
                
                //得到当前子菜单
                $zEdu = new ZEdu();
                
                $menu_ids = '';
                $where = ' WHERE "parentid" = '.$mid;
                $menuId = $zEdu->_getMenuData($where);
                if(!empty($menuId)){
                    
                    $mArr = array();
                    foreach($menuId as $mVal){
                        $mArr[] = $mVal['id'];
                    }
                    $menu_ids = implode(',', $mArr);
                    if(!empty($menu_ids)){
                        $dsql = 'DELETE FROM "{{menu}}" WHERE "id" IN('.$menu_ids.")";
                        $res = Yii::app()->db->createCommand($dsql);
                        $res->execute();
                    }
                    
                }
                
            }
        }
 
        echo $status;
    }
    
    /**
     * 当前角色的功能
     * 
     * @author jinyue.wang
     * @version 1.0
     * @date 2013-12-29
     */
    public function actionPrive(){
        
        $this->layout = "//layouts/main_window";
        
        $zEdu = new ZEdu();
        $role_id = $this->request->getParam('role_id');

        $tree = new Tree();
        $tree->icon = array('&nbsp;│ ', '&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;';
        
        //得到用户权限
        $rolePrive = $zEdu->_getRolePrive($role_id);
        
        $where = 'WHERE "display" = 1 ';
        $menuArray  = $zEdu->_getMenuData($where);

        if(!empty($menuArray)){
            foreach($menuArray as $key => $value){
                $check = '';
                if ($role_id == 1) {
                    $check = 'checked';
                } else {
                    if (in_array($value['id'], $rolePrive)): $check = 'checked';
                    endif;
                }
                $menuArray[$key]['cbox'] = " <input type='checkbox' disabled='' name='menu_id[]' " . $check . " value='" . $value['id'] . "'>";

                $menuArray[$key]['ckey'] = '';
                if ($value['parentid'] == 0) {
                    $menuArray[$key]['ckey'] = "<a class='cursor click_on'><img src='" . THEME_IMAGES_URL . "/Sipei/uAdd.png'></a>";
                }
            }
        }
        
        $str = "<ul class='treeBox'>
                    <li>\$spacer\$ckey\$cname\$cbox</li>
                </ul>";
        
        $tree->init($menuArray);
        $list = $tree->get_tree(0, $str);
        
        $this->render('prive',array(
            'list'  => $list
        ));
    }
    
}